package com.vecspace.dicttable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**缓存字典数据的类
 * 字典数据获取之后存储到itemList，最后还会同时存储到Map items中，方便获取名称值
 * @author: wanghua
 */
public class CodeTable {
	private String tableName; 
	private String idField;
	private String codeField;
	private String nameField;
	private String orderByField;
	private List<CodeItem> itemList;
	private Map<String,CodeItem> items;
	
	public CodeTable(){
		itemList = new ArrayList<CodeItem>();
		items = new HashMap<String,CodeItem>();
	}
	
	public CodeTable(String tableName){
		itemList = new ArrayList<CodeItem>();
		this.tableName = tableName;
		items = new HashMap<String,CodeItem>();
	}
	
	/**
	 * 添加一个字典项
	 * 功能描述：
	 * @param item 
	 * @author: wanghua
	 */
	public void addDMItem(CodeItem item){
		itemList.add(item);
	}
	
	/**
	 * 根据编码获取名称
	 * 功能描述：
	 * @param code 编码值，可以是数字或者字符串。这里code定义为Object类型
	 * @return 
	 * @author: wanghua
	 */
	public String getName(Object code){		 
		CodeItem item = getItem(code);
		if(item == null) {
			return code.toString();
		}
		else {
			return item.getName();
		}
	}
	
	/** 根据编码获取DMItem
	 * 功能描述：
	 * @param code 编码值，可以是数字或者字符串。这里code定义为Object类型
	 * @return 
	 * @author: wanghua
	 */
	public CodeItem getItem(Object code){
		if(code == null) {
			return null;
		}
		if(items.size()==0 && itemList.size()>0){
			synchronized(this){
				if(items.size()==0 && itemList.size()>0){
					for(CodeItem item : itemList){
						items.put(item.getCode().toString(), item);
					}
				}
			}
		}
		CodeItem item = items.get(code.toString());
		return item;
	}
	
	public String getTableName(){
		return tableName;
	}

	public List<CodeItem> getItemlist() {
		return itemList;
	}

	public void setItemlist(List<CodeItem> itemlist) {
		this.itemList = itemlist;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

	public String getIdField() {
		return idField;
	}

	public void setIdField(String idField) {
		this.idField = idField;
	}

	public String getCodeField() {
		return codeField;
	}

	public void setCodeField(String codeField) {
		this.codeField = codeField;
	}

	public String getNameField() {
		return nameField;
	}

	public void setNameField(String nameField) {
		this.nameField = nameField;
	}

	public String getOrderByField() {
		return orderByField;
	}

	public void setOrderByField(String orderByField) {
		this.orderByField = orderByField;
	}
}
